const express = require('express');
const redis = require('redis');
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = 8080;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// Redis客户端
const redisClient = redis.createClient({
    host: 'localhost',
    port: 6379
});

// 连接Redis
redisClient.connect().catch(console.error);

redisClient.on('error', (err) => {
    console.log('Redis连接错误:', err);
});

redisClient.on('connect', () => {
    console.log('Redis连接成功');
});

// 初始化默认数据
async function initDefaultData() {
    try {
        // 等待Redis连接完成
        if (!redisClient.isReady) {
            await new Promise(resolve => {
                redisClient.once('ready', resolve);
            });
        }
        
        // 检查是否已有数据
        const hasData = await redisClient.exists('navigation:my');
        if (!hasData) {
            // 我的导航
            await redisClient.hSet('navigation:my', '百度', 'https://www.baidu.com');
            await redisClient.hSet('navigation:my', '谷歌', 'https://www.google.com');
            
            // AI工具
            await redisClient.hSet('navigation:ai', 'ChatGPT', 'https://chat.openai.com');
            await redisClient.hSet('navigation:ai', 'Claude', 'https://claude.ai');
            
            // 商城购物
            await redisClient.hSet('navigation:shopping', '淘宝', 'https://www.taobao.com');
            await redisClient.hSet('navigation:shopping', '京东', 'https://www.jd.com');
            
            // 视频娱乐
            await redisClient.hSet('navigation:entertainment', '哔哩哔哩', 'https://www.bilibili.com');
            await redisClient.hSet('navigation:entertainment', '优酷', 'https://www.youku.com');
            
            // 新闻资讯
            await redisClient.hSet('navigation:news', '新浪新闻', 'https://news.sina.com.cn');
            await redisClient.hSet('navigation:news', '腾讯新闻', 'https://news.qq.com');
            
            console.log('默认数据初始化完成');
        }
    } catch (error) {
        console.log('初始化数据失败:', error);
    }
}

// API路由

// 获取所有导航数据
app.get('/api/navigation', async (req, res) => {
    try {
        const categories = ['my', 'ai', 'shopping', 'entertainment', 'news'];
        const result = {};
        
        for (const category of categories) {
            const links = await redisClient.hGetAll(`navigation:${category}`);
            result[category] = links;
        }
        
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

// 添加链接
app.post('/api/navigation/:category', async (req, res) => {
    try {
        const { category } = req.params;
        const { name, url } = req.body;
        
        if (!name || !url) {
            return res.status(400).json({ error: '名称和URL不能为空' });
        }
        
        await redisClient.hSet(`navigation:${category}`, name, url);
        res.json({ message: '添加成功' });
    } catch (error) {
        res.status(500).json({ error: '添加失败' });
    }
});

// 删除链接
app.delete('/api/navigation/:category/:name', async (req, res) => {
    try {
        const { category, name } = req.params;
        await redisClient.hDel(`navigation:${category}`, name);
        res.json({ message: '删除成功' });
    } catch (error) {
        res.status(500).json({ error: '删除失败' });
    }
});

// 更新链接
app.put('/api/navigation/:category/:name', async (req, res) => {
    try {
        const { category, name } = req.params;
        const { newName, url } = req.body;
        
        if (!newName || !url) {
            return res.status(400).json({ error: '新名称和URL不能为空' });
        }
        
        // 先删除旧的，再添加新的
        await redisClient.hDel(`navigation:${category}`, name);
        await redisClient.hSet(`navigation:${category}`, newName, url);
        
        res.json({ message: '更新成功' });
    } catch (error) {
        res.status(500).json({ error: '更新失败' });
    }
});

// 启动服务器
app.listen(PORT, async () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
    await initDefaultData();
});
